package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.redis.service.RedisService;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.order.domain.OrderSupplierManagement;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.PurchaseReceiptExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.utils.VariousKeyEnum;
import com.pureut.storage.vo.PurchaseVo;
import com.pureut.storage.vo.UpdateReceiptStatusVo;
import com.pureut.storage.vo.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.OrderFeignService;
import com.pureut.system.api.QualityFeginService;
import com.pureut.system.api.SystemDocumentFeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.dto.PurchaseOrderDto;
import com.pureut.system.api.vo.MaterialVo;
import com.pureut.system.api.vo.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/***
 *
 * Author:C
 * Date:2022/12/23 10:14
 * @DESC
 */
@Service
public class PurchaseReceiptServiceImpl extends ServiceImpl<PurchaseReceiptMapper, PurchaseReceipt> implements PurchaseReceiptService {

    @Resource
    PurchaseReceiptMapper purchaseReceiptMapper;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    WarehouseService warehouseService;

    @Resource
    FeignService feignService;

    @Resource
    RedisService redisService;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    @Lazy
    @Resource
    IncomingMaterialPrintingService incomingMaterialPrintingService;

    @Resource
    IncomingMaterialPrintingDetailService incomingMaterialPrintingDetailService;

    @Resource
    PurchaseReceiptDetailMapper purchaseReceiptDetailMapper;

    @Resource
    PurchaseReceiptDetailService purchaseReceiptDetailService;

    @Resource
    WmsStockInfoService wmsStockInfoService;

    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    QualityFeginService qualityFeginService;

    @Resource
    SystemDocumentFeignService systemDocumentFeignService;

    @Resource
    OrderSupplierManagementService orderSupplierManagementService;

    @Resource
    WipCompletionMapper wipCompletionMapper;

    @Resource
    ProductionMaterialReturnMapper productionMaterialReturnMapper;

    @Resource
    SalesReturnMapper salesReturnMapper;

    @Resource
    SubcontractReceiptMapper subcontractReceiptMapper;

    @Resource
    MiscellaneousReceiptMapper miscellaneousReceiptMapper;

    @Resource
    ProductionMaterialReturnService productionMaterialReturnService;

    @Resource
    SalesReturnService salesReturnService;

    @Resource
    MiscellaneousReceiptService miscellaneousReceiptService;

    @Resource
    WipCompletionService wipCompletionService;

    //生产领料
    @Resource
    ProductionPickingMapper productionPickingMapper;

    @Resource
    ProductionPickingService productionPickingService;

    //委外发货
    @Resource
    PickingOutsourceMapper pickingOutsourceMapper;

    @Resource
    PickingOutsourceService pickingOutsourceService;

    //销售发货
    @Resource
    PickingSaleMapper pickingSaleMapper;

    @Resource
    PickingSaleService pickingSaleService;

    //采购退货
    @Resource
    PickingPurchaseMapper pickingPurchaseMapper;

    @Resource
    PickingPurchaseService pickingPurchaseService;

    //委外退货
    @Resource
    PickingReturnsMapper pickingReturnsMapper;

    @Resource
    PickingReturnsService pickingReturnsService;

    //返工出库
    @Resource
    PickingCompleteMapper pickingCompleteMapper;
    @Resource
    PickingCompleteService pickingCompleteService;

    //其他出库
    @Resource
    PickingRestMapper pickingRestMapper;

    @Resource
    PickingRestService pickingRestService;

    //调拨单
    @Resource
    AllotManagementMapper allotManagementMapper;

    @Resource
    AllotManagementService allotManagementService;

    @Resource
    IncomingMaterialPrintingDetailMapper incomingMaterialPrintingDetailMapper;

    @Resource
    IncomingMaterialPrintingMapper incomingMaterialPrintingMapper;

    /**
     * 获取采购入库列表
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<PurchaseReceiptDto> getReceiptList(PurchaseReceiptVo purchaseReceiptVo) {
        List<PurchaseReceiptDto> receiptList = purchaseReceiptMapper.getReceiptList(purchaseReceiptVo);
        //获取采购入库状态字典值
        List<SysDictData> receiptArray = DictUtils.getDictCache("purchase_receipt_status");
        Map<String, String> purchaseReceiptMap = receiptArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取采购入库收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("purchase_receipt_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (PurchaseReceiptDto entity : receiptList) {
            //采购入库状态字典值
            entity.setStatus(entity.getStatus());
            entity.setStatusDict(purchaseReceiptMap.get(entity.getStatus()));
            //物料单位
            entity.setMaterialUnitDict(unitMap.get(entity.getMaterialUnit()));
            //单据类型
            entity.setDocumentType(entity.getDocumentType());
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
            //收发类型
            entity.setReceiveType(entity.getReceiveType());
            entity.setReceiveTypeDict(rdMap.get(entity.getReceiveType()));
            //生成方式
            entity.setGenerationMethod(entity.getGenerationMethod());
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(Integer.parseInt(entity.getGenerationMethod())));
            //免检标识
            InspectionMarkVo inspectionMarkVo = new InspectionMarkVo();
            inspectionMarkVo.setSupplierId(entity.getSupplierId());
            inspectionMarkVo.setMaterialCode(entity.getMaterialCode());
            AjaxResult inspectionMark = qualityFeginService.getInspectionMark(inspectionMarkVo);
            if (inspectionMark == null) {
                entity.setInspectionExemption(2);
            } else {
                QualityInspectionManagementDto data = JSON.parseObject(JSON.toJSONString(inspectionMark.get("data")), QualityInspectionManagementDto.class);
                if (data.getId() == null) {
                    entity.setInspectionExemption(2);
                } else {
                    entity.setInspectionExemption(data.getStatus());
                }
            }
        }
        return receiptList;
    }

    /**
     * 新增
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addReceipt(PurchaseReceiptVo purchaseReceiptVo) throws Exception {

        List<PurchaseVo> procurementList = purchaseReceiptVo.getProcurementList();
        List<PurchaseReceipt> purchaseReceiptArrayList = new ArrayList<>();
        if (procurementList.size() > 0) {
            for (PurchaseVo entity : procurementList) {
                PurchaseReceipt purchaseReceipt = new PurchaseReceipt();
                String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:purchase:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                purchaseReceipt.setReceiptNo(feignService.splitList("CGRK"))
                        .setDeptId(SecurityUtils.getDeptId())
                        .setStatus(1)
                        .setPurchaseOrderNo(entity.getPurchaseOrderNo())
                        .setMaterialId(entity.getMaterialId())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialCategory(entity.getMaterialCategory())
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(Long.parseLong(entity.getWarehousingWarehouse()))
                        .setSupplierId(purchaseReceiptVo.getSupplierId())
                        .setEstimatedTime(purchaseReceiptVo.getEstimatedTime())
                        .setRemark(purchaseReceiptVo.getRemark())
                        .setDrawerBy(SecurityUtils.getUsername())
                        .setDrawerTime(new Date())
                        .setReceiveType(purchaseReceiptVo.getReceiveType())
                        .setDocumentType(DocumentTypeEnum.PURCHASE_RECEIPT.getCode())
                        .setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                purchaseReceiptArrayList.add(purchaseReceipt);
            }
            return saveBatch(purchaseReceiptArrayList);
        } else {
            throw new GlobalException("请至少选择一条数据");
        }
    }

    /**
     * 批次到货新增
     *
     * @param purchaseOrderDto
     * @return
     */
    @Override
    public boolean batchArrival(PurchaseOrderDto purchaseOrderDto) throws Exception {
        List<MaterialVo> materialList = purchaseOrderDto.getMaterialList();
        PurchaseReceipt purchaseReceipt = new PurchaseReceipt();
        for (MaterialVo entity : materialList) {
            String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:purchase:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            purchaseReceipt.setReceiptNo(authorityCoding)
                    .setDeptId(SecurityUtils.getDeptId())
                    .setPlannedWeight(Double.parseDouble(purchaseOrderDto.getMaterialList().get(0).getQuantityArrivalTimeWeight()))
                    .setStatus(1)
                    .setPurchaseOrderNo(purchaseOrderDto.getPurchaseOrderNo())
                    .setMaterialId(entity.getMaterialId())
                    .setMaterialCode(entity.getMaterialCode())
                    .setMaterialCategory(Integer.parseInt(purchaseOrderDto.getMaterialCategory()))
                    .setSupplierId(purchaseOrderDto.getSupplierId())
                    .setEstimatedTime(purchaseOrderDto.getEstimatedTime())
                    .setDrawerBy(SecurityUtils.getUsername())
                    .setDrawerTime(new Date())
                    .setDocumentType(DocumentTypeEnum.PURCHASE_RECEIPT.getCode())
                    .setGenerationMethod(GenerationMethodEnum.AUTO_GENERATE.getCode());
        }
        return save(purchaseReceipt);
    }

    /**
     * 关结
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(PurchaseReceiptVo purchaseReceiptVo) {

        PurchaseReceipt purchaseReceipt = getById(purchaseReceiptVo.getId());

        //判断来料打印中是否都已完成，否则不让关结
        List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(new QueryWrapper<IncomingMaterialPrinting>().lambda()
                .eq(IncomingMaterialPrinting::getReceiptNo, purchaseReceipt.getReceiptNo())
                .ne(IncomingMaterialPrinting::getPrintStatus, 4));

        if (incomingMaterialPrintings.size() != 0) {
            throw new GlobalException("存在未完成的来料打印单,不能关结");
        }


        //已完成、已关结不可重复关结；
        if (purchaseReceipt.getStatus() != 3 || purchaseReceipt.getStatus() != 4) {
            //待入库状态的单据关结后，单据状态更新为“已关结”，无影响；
            if (purchaseReceipt.getStatus() == 1) {
                purchaseReceipt.setStatus(4)
                        .setCloseReason(purchaseReceiptVo.getCloseReason())
                        .setClosingBy(SecurityUtils.getUsername())
                        .setClosingTime(new Date());
            }
            //入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库（采购入库未扫描到的条码从库存中删除）
            if (purchaseReceipt.getStatus() == 2) {
                List<PurchaseReceiptDetail> purchaseReceiptDetails = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));
                if (purchaseReceiptDetails.size() > 0) {
                    //获取未扫描的明细数据
                    List<String> materialNumberList = purchaseReceiptDetails.stream()
                            .filter(t -> t.getStatus() == 1)
                            .map(PurchaseReceiptDetail::getMaterialNumber)
                            .collect(Collectors.toList());
                    //将对应号码的数据在仓库中进行删除
                    if(materialNumberList.size() != 0){
                        List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                        wmsStockInfoService.removeBatchByIds(wmsStockInfos);
                    }
                }
                purchaseReceipt.setStatus(4)
                        .setCloseReason(purchaseReceiptVo.getCloseReason())
                        .setClosingBy(SecurityUtils.getUsername())
                        .setClosingTime(new Date());
            }
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }
        return updateById(purchaseReceipt);


    }


    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public PurchaseReceiptDto getView(Long id) {
        PurchaseReceiptDto receiptViewById = purchaseReceiptMapper.getReceiptViewById(id);
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单据类型
        receiptViewById.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(receiptViewById.getDocumentType())));
        //收发类型
        List<SysDictData> typeArray = DictUtils.getDictCache("purchase_receipt_rd_type");
        Map<String, String> purchaseReceiptMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        receiptViewById.setReceiveTypeDict(purchaseReceiptMap.get(receiptViewById.getReceiveType()));

        List<PurchaseVo> purchaseVos = new ArrayList<>();
        PurchaseVo purchaseVo = new PurchaseVo();
        purchaseVo.setPurchaseOrderNo(receiptViewById.getPurchaseOrderNo());
        purchaseVo.setPlannedWeight(receiptViewById.getPlannedWeight());
        purchaseVo.setWarehousingWarehouse(receiptViewById.getWarehousingWarehouse());
        //物料单位
        purchaseVo.setMaterialUnit(receiptViewById.getMaterialUnit());
        purchaseVo.setUnitDict(unitMap.get(receiptViewById.getMaterialUnit()));
        //获取仓库名称
        purchaseVo.setWarehousingWarehouseDict(receiptViewById.getWarehousingWarehouseDict());
        purchaseVo.setMaterialName(receiptViewById.getMaterialName());
        purchaseVo.setMaterialCode(receiptViewById.getMaterialCode());
        purchaseVo.setMaterialSpec(receiptViewById.getMaterialSpec());

        purchaseVos.add(purchaseVo);
        receiptViewById.setProcurementList(purchaseVos);
        return receiptViewById;
    }


    /**
     * 修改
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReceipt(PurchaseReceiptVo purchaseReceiptVo) {
        PurchaseReceipt purchaseReceipt = getById(purchaseReceiptVo.getId());
        if (purchaseReceipt.getGenerationMethod() == 1) {
            throw new GlobalException("自动生成的单据不可修改");
        }
        if (purchaseReceipt.getStatus() == 1) {
            purchaseReceipt.setReceiveType(purchaseReceiptVo.getReceiveType());
            purchaseReceipt.setSupplierId(purchaseReceiptVo.getSupplierId());
            purchaseReceipt.setEstimatedTime(purchaseReceiptVo.getEstimatedTime());
            purchaseReceipt.setRemark(purchaseReceiptVo.getRemark());
            List<PurchaseVo> procurementList = purchaseReceiptVo.getProcurementList();
            for (PurchaseVo entity : procurementList) {
                purchaseReceipt.setPurchaseOrderNo(entity.getPurchaseOrderNo())
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(Long.parseLong(entity.getWarehousingWarehouse()))
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialId(entity.getMaterialId());
            }
            return updateById(purchaseReceipt);
        } else {
            throw new GlobalException("只能修改待入库的数据");
        }

    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean deleteReceipt(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("请至少选择一条数据");
        }
        List<PurchaseReceipt> purchaseReceiptList = new ArrayList<>();
        List<PurchaseReceipt> purchaseReceipts = purchaseReceiptMapper.selectList(new QueryWrapper<PurchaseReceipt>().lambda().in(PurchaseReceipt::getId, idList));
        for (PurchaseReceipt entity : purchaseReceipts) {
            if (entity.getStatus() == 1) {
                purchaseReceiptList.add(entity);
            } else {
                throw new GlobalException("只能删除待入库的单据");
            }
        }
        List<PurchaseReceipt> deleteList = new ArrayList<>();
        for (PurchaseReceipt entity : purchaseReceiptList) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        return removeByIds(deleteList);
    }


    /**
     * 入库/送检
     *
     * @param warehousInspectionVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean warehousInspection(WarehousInspectionVo warehousInspectionVo) throws Exception {
        PurchaseReceipt purchaseReceipt = getById(warehousInspectionVo.getId());
        //获取供应商信息
        OrderSupplierManagement supplierManagement = orderSupplierManagementService.getById(purchaseReceipt.getSupplierId());
        if (purchaseReceipt.getStatus() == 1 || purchaseReceipt.getStatus() == 2) {
            //修改状态为入库中
            purchaseReceipt.setStatus(2);

            List<InspectionVo> warehousInspectionList = warehousInspectionVo.getInspectionList();

            for (InspectionVo entity : warehousInspectionList) {
                List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = new ArrayList<>();
                IncomingMaterialPrinting incomingMaterialPrinting = new IncomingMaterialPrinting();
                incomingMaterialPrinting.setDocumentType(purchaseReceipt.getDocumentType())
                        .setDeptId(SecurityUtils.getDeptId())
                        .setReceiptNo(purchaseReceipt.getReceiptNo())
                        .setSupplierId(purchaseReceipt.getSupplierId())
                        .setQuantityBatch(entity.getNumberCars())
                        .setCreateBy(SecurityUtils.getUsername())
                        .setCreateTime(new Date())
                        //唯一标识
                        .setOnlyMark(feignService.splitList("IMP"))
                        //生成批次号
                        .setBatchNo(batchNoGenerate())
                        .setMaterialCode(purchaseReceipt.getMaterialCode());
                //如果是免检就保存打印状态为待打印，如果不是就保存待检验
                if (warehousInspectionVo.getInspectionExemption() == 1) {
                    incomingMaterialPrinting.setPrintStatus(2);
                } else {
                    incomingMaterialPrinting.setPrintStatus(1);
                }
                incomingMaterialPrintingService.save(incomingMaterialPrinting);
                //存储打印明细数据
                for (int i = 0; i <= entity.getNumberCars() - 1; i++) {
                    IncomingMaterialPrintingDetail incomingMaterialPrintingDetail = new IncomingMaterialPrintingDetail();
                    incomingMaterialPrintingDetail.setPrintId(incomingMaterialPrinting.getId())
                            .setBatchNo(incomingMaterialPrinting.getBatchNo())
                            .setReceiptQuantity(1)
                            .setMaterialCategory(purchaseReceipt.getMaterialCategory())
                            .setMaterialId(purchaseReceipt.getMaterialId())
                            .setMaterialCode(incomingMaterialPrinting.getMaterialCode())
                            .setMaterialNumber(feignService.splitList("CGRKDYNUM"))
                            .setReceiptId(purchaseReceipt.getId());
                    //如果是免检就保存净重和毛重数据
                    if (warehousInspectionVo.getInspectionExemption() == 1) {
                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
                        incomingMaterialPrintingDetail.setNetWeight(entity.getNetWeight() / entity.getNumberCars());
                    } else {
                        incomingMaterialPrintingDetail.setGrossWeight(entity.getNetWeight() / entity.getNumberCars());
                    }
                    incomingMaterialPrintingDetails.add(incomingMaterialPrintingDetail);
                }
                incomingMaterialPrintingDetailService.saveBatch(incomingMaterialPrintingDetails);

                // 生成品质检验单
                if (incomingMaterialPrinting.getPrintStatus() == 1) {
                    Long menuId = feignService.getIdByMenuName("采购入库");
                    AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                    SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
                    if (sysDocument.getDocCode() == null) {
                        throw new GlobalException("未找到相应的检验项目，请前往“质量管理“---”检验配置”页配置");
                    }
                    List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                    if (documentCheckDtoList.size() < 1) {
                        throw new GlobalException("未进行检验单生成配置");
                    }
                    //通过物料编码获取物料类别
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseReceipt.getMaterialCode()));


                    for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                        if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                            qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualityInspectionDocumentVo.setMaterialCode(purchaseReceipt.getMaterialCode());
                            qualityInspectionDocumentVo.setBatchNo(incomingMaterialPrinting.getBatchNo());
                            qualityInspectionDocumentVo.setAssociatedNo(incomingMaterialPrinting.getReceiptNo());
                            qualityInspectionDocumentVo.setOnlyMark(incomingMaterialPrinting.getOnlyMark());
                            qualityInspectionDocumentVo.setDifferentString(supplierManagement.getSupplierNum());
                            qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                            qualityInspectionDocumentVo.setModeType(10);

                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                            for (IncomingMaterialPrintingDetail detail : incomingMaterialPrintingDetails) {
                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setBatchNo(detail.getBatchNo());
                                materialNumberAndBatchNoVo.setMaterialNumber(detail.getMaterialNumber());
                                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                            }
                            qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                            AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
                            String code = add.get("code").toString();
                            if ("500".equals(code)) {
                                throw new GlobalException("生成品质检验单失败!");
                            }
                        } else {
                            throw new GlobalException("所选物料和送检物料类型不一致，请核实相关配置");
                        }
                    }
                }
            }
            return updateById(purchaseReceipt);
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }

    /**
     * 导出
     *
     * @param purchaseReceiptVo
     * @return
     */
    @Override
    public List<PurchaseReceiptExport> getInfoExport(PurchaseReceiptVo purchaseReceiptVo) {
        List<PurchaseReceiptExportDto> purchaseReceipts;

        if (purchaseReceiptVo.getIdStr() == null) {
            purchaseReceipts = purchaseReceiptMapper.getReceiptListOut(purchaseReceiptVo);
        } else {
            List<String> idList = Arrays.asList(purchaseReceiptVo.getIdStr().split(","));
            purchaseReceipts = purchaseReceiptMapper.getDataByIdStr(idList);
        }

        //采购入库收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("purchase_receipt_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<PurchaseReceiptExport> exportList = new ArrayList<>();
        for (PurchaseReceiptExportDto entity : purchaseReceipts) {
            PurchaseReceiptExport purchaseReceiptExport = new PurchaseReceiptExport();

            BeanUtils.copyProperties(entity, purchaseReceiptExport);
            //供应商
            purchaseReceiptExport.setSupplierName(entity.getSupplierName());

            //收发类型
            if (!"0".equals(entity.getReceiveType())) {
                purchaseReceiptExport.setReceiveType(rdMap.get(String.valueOf(entity.getReceiveType())));
            } else {
                purchaseReceiptExport.setReceiveType("");
            }
            exportList.add(purchaseReceiptExport);
        }
        return exportList;
    }

    /**
     * 采购入库 pda入库
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto warehousingPda(PickingRestDbVo pickingRestDbVo) {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        PurchaseReceipt byId = getById(pickingRestDbVo.getId());
        if (byId.getStatus() == 1 || byId.getStatus() == 2) {
            //扫码入库
            if ("1".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setCode("200");
                    pickingRestDbDto.setMessage("操作成功");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    PurchaseReceiptDetail purchaseReceiptDetail = purchaseReceiptDetailMapper.selectOne(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                    if (purchaseReceiptDetail == null) {
                        pickingRestDbDto.setMessage("不存在该明细，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    if (purchaseReceiptDetail.getStatus() == 2) {
                        pickingRestDbDto.setMessage("该数据已经入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    PurchaseReceipt purchaseReceipt = getById(pickingRestDbVo.getId());
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseReceiptDetail.getMaterialCode()));
                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                    //如果单位是千克
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        if (purchaseReceipt.getActualQuantity() == null) {
                            purchaseReceipt.setActualQuantity(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            //修改采购入库信息入库重量
                            purchaseReceipt.setWarehousingWeight(purchaseReceiptDetail.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            purchaseReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                        if (purchaseReceipt.getActualQuantity() == null) {
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                            purchaseReceipt.setActualQuantity(divide.toString());
                            //修改采购入库信息入库重量
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(divide.toString()));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                            String s = bigDecimal.add(divide).toString();
                            purchaseReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            BigDecimal divide1 = bigDecimal3.divide(new BigDecimal("1000"));
                            String s1 = bigDecimal2.add(divide1).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else {
                        //如果单位是克（后期可能会修改为包）
                        if (purchaseReceipt.getActualQuantity() == null) {
                            purchaseReceipt.setActualQuantity(String.valueOf(purchaseReceiptDetail.getReceiptQuantity()));
                            //修改采购入库信息入库重量
                            purchaseReceipt.setWarehousingWeight(purchaseReceiptDetail.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getReceiptQuantity()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            purchaseReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(purchaseReceiptDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    }

                    //设置入库仓
                    purchaseReceipt.setWarehousingWarehouse(pickingRestDbVo.getCkId());
                    //设置入库数量
                    int warehousingNum1 = purchaseReceipt.getWarehousingNum();
                    if (warehousingNum1 == 0) {
                        purchaseReceipt.setWarehousingNum(1);
                    } else {
                        purchaseReceipt.setWarehousingNum(warehousingNum1 + 1);
                    }

                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setMessage("物料号码:" + purchaseReceiptDetail.getMaterialNumber() + "," + "净重:" + purchaseReceiptDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + purchaseReceiptDetail.getReceiptQuantity() + "," + "录入成功");
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(purchaseReceipt.getWarehousingNum()));

                    //修改仓库表中对应的数据状态
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, purchaseReceiptDetail.getMaterialNumber()));
                    wmsStockInfo.setWsiMaterialStatus(2);
                    wmsStockInfo.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                    wmsStockInfo.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                    wmsStockInfo.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                    wmsStockInfo.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                    wmsStockInfo.setWsiDocNum(byId.getReceiptNo());
                    wmsStockInfo.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                    wmsStockInfo.setWsiMaterialType(publicGoods.getMaterialType());
                    wmsStockInfo.setWsiReveiveTime(new Date());
                    wmsStockInfo.setWsiConnectNum(byId.getPurchaseOrderNo());
                    wmsStockInfo.setWsiMaterialGrade("1");
                    wmsStockInfoService.updateById(wmsStockInfo);
                    //修改明细状态
                    purchaseReceiptDetail.setStatus(2);
                    purchaseReceiptDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                    purchaseReceiptDetail.setWarehouseInTime(new Date());
                    purchaseReceiptDetail.setWarehouseInBy(SecurityUtils.getUsername());
                    purchaseReceiptDetailService.updateById(purchaseReceiptDetail);
                    //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        if (entity.getStatus() == 1) {
                            isTrue = false;
                            break;
                        }
                    }


                    boolean b;
                    //实际量
                    double aDouble = Double.parseDouble(purchaseReceipt.getActualQuantity());
                    //单位为千克或者吨
                    if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                        double plannedWeight = purchaseReceipt.getPlannedWeight();
                        b = (int) Math.round(aDouble) >= (int) Math.round(plannedWeight);
                    } else {
                        int warehousingNum = purchaseReceipt.getWarehousingNum();
                        b = (int) Math.round(aDouble) >= warehousingNum;
                    }

                    if (isTrue && b) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);
                    }

                    if (purchaseReceipt.getStatus() == 3) {
                        // 将数据回传至采购订单
                        UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
                        updatePurchaseOrderDataVo.setActualQuantity(purchaseReceipt.getActualQuantity());
                        updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
                        orderFeignService.updateOrderData(updatePurchaseOrderDataVo);
                    }
                    //修改打印数据状态
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList1 = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, purchaseReceipt.getId()));

                    Map<String, List<PurchaseReceiptDetail>> collect = purchaseReceiptDetailList1.stream().collect(Collectors.groupingBy(PurchaseReceiptDetail::getBatchNo));
                    for (Map.Entry<String, List<PurchaseReceiptDetail>> materialGroupEntity : collect.entrySet()) {
                        boolean isAll = true;
                        for (PurchaseReceiptDetail entity1 : materialGroupEntity.getValue()) {
                            if (entity1.getStatus() != 2) {
                                isAll = false;
                                break;
                            }
                        }
                        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, purchaseReceipt.getReceiptNo()).eq(IncomingMaterialPrinting::getBatchNo, materialGroupEntity.getKey()));
                        if (isAll) {
                            //把对应的来料打印数据状态修改为已完成
                            incomingMaterialPrinting.setPrintStatus(4);
                        } else {
                            //把对应的来料打印数据状态修改为待入库
                            incomingMaterialPrinting.setPrintStatus(3);
                        }
                        incomingMaterialPrintingService.updateById(incomingMaterialPrinting);
                    }
                    //判断该单据在打印页面是否还存在未入库数据
                    String receiptNo = purchaseReceipt.getReceiptNo();
                    List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, receiptNo));
                    boolean printAll = true;
                    for (IncomingMaterialPrinting entity : incomingMaterialPrintings) {
                        if (entity.getPrintStatus() != 4) {
                            printAll = false;
                            break;
                        }
                    }
                    if (printAll) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);
                    }
                    updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
            }
            //批次入库
            if ("2".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据批次号查询明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getBatchNo, pickingRestDbVo.getInputValue()).eq(PurchaseReceiptDetail::getStatus, 1));
                    if (purchaseReceiptDetailList.size() < 1) {
                        pickingRestDbDto.setMessage("该批次号下无待入库数据，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    //净重总数
                    BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                    //入库数量总数
                    BigDecimal bigDecimalWarehouseNum = new BigDecimal(0);
                    //循环明细信息
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                        bigDecimalWarehouseNum = bigDecimalWarehouseNum.add(new BigDecimal(String.valueOf(entity.getReceiptQuantity())));
                    }
                    //获取采购入库信息
                    PurchaseReceipt purchaseReceipt = getById(pickingRestDbVo.getId());
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseReceipt.getMaterialCode()));
                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                    //判断单位
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是千克
                        if (purchaseReceipt.getActualQuantity() == null) {
                            purchaseReceipt.setActualQuantity(bigDecimalNetWeight.toString());
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            String s = bigDecimal.add(bigDecimalNetWeight).toString();
                            purchaseReceipt.setActualQuantity(s);

                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            String s1 = bigDecimal1.add(bigDecimalNetWeight).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                        if (purchaseReceipt.getActualQuantity() == null) {
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(bigDecimalNetWeight.toString()));
                            BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"), 1);
                            purchaseReceipt.setActualQuantity(divide.toString());
                            //修改采购入库信息入库重量
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(divide.toString()));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(bigDecimalNetWeight.toString()));
                            BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"), 1);
                            String s = bigDecimal.add(divide).toString();
                            purchaseReceipt.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(bigDecimalNetWeight.toString()));
                            BigDecimal divide1 = bigDecimal3.divide(new BigDecimal("1000"), 1);
                            String s1 = bigDecimal2.add(divide1).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else {
                        if (purchaseReceipt.getActualQuantity() == null) {
                            purchaseReceipt.setActualQuantity(bigDecimalWarehouseNum.toString());
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(purchaseReceipt.getActualQuantity());
                            String s = bigDecimal.add(bigDecimalWarehouseNum).toString();
                            purchaseReceipt.setActualQuantity(s);

                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseReceipt.getWarehousingWeight()));
                            String s1 = bigDecimal1.add(bigDecimalNetWeight).toString();
                            purchaseReceipt.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    }
                    //设置入库仓
                    purchaseReceipt.setWarehousingWarehouse(pickingRestDbVo.getCkId());
                    //设置入库数量
                    int warehousingNum1 = purchaseReceipt.getWarehousingNum();
                    if (warehousingNum1 == 0) {
                        purchaseReceipt.setWarehousingNum(purchaseReceiptDetailList.size());
                    } else {
                        purchaseReceipt.setWarehousingNum(warehousingNum1 + purchaseReceiptDetailList.size());
                    }

                    //设置返回值
                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setMessage("批次号:" + purchaseReceiptDetailList.get(0).getBatchNo() + "," + "净重:" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + purchaseReceiptDetailList.size() + "," + "录入成功");
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(bigDecimalWarehouseNum));


                    //修改仓库表中对应的数据状态
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    List<WmsStockInfo> wmsStockInfoArrayList = new ArrayList<>();
                    for (WmsStockInfo entity : wmsStockInfoList) {
                        entity.setWsiMaterialStatus(2);
                        entity.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                        entity.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                        entity.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                        entity.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                        entity.setWsiDocNum(byId.getReceiptNo());
                        entity.setWsiConnectNum(byId.getPurchaseOrderNo());
                        entity.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                        entity.setWsiMaterialType(publicGoods.getMaterialType());
                        entity.setWsiReveiveTime(new Date());
                        entity.setWsiMaterialGrade("1");
                        wmsStockInfoArrayList.add(entity);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfoArrayList);
                    //修改明细状态
                    List<PurchaseReceiptDetail> detailList = new ArrayList<>();
                    for (PurchaseReceiptDetail receiptDetail : purchaseReceiptDetailList) {
                        receiptDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                        receiptDetail.setWarehouseInTime(new Date());
                        receiptDetail.setWarehouseInBy(SecurityUtils.getUsername());
                        receiptDetail.setStatus(2);
                        detailList.add(receiptDetail);
                    }
                    purchaseReceiptDetailService.updateBatchById(detailList);
                    //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
                    List<PurchaseReceiptDetail> receiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (PurchaseReceiptDetail entity : receiptDetailList) {
                        if (entity.getStatus() == 1) {
                            isTrue = false;
                            break;
                        }
                    }

                    //单位为千克
                    boolean b;
                    //实际量
                    double aDouble = Double.parseDouble(purchaseReceipt.getActualQuantity());
                    if ("2".equals(publicGoods.getMaterialUnit()) || "3".equals(publicGoods.getMaterialUnit())) {
                        double plannedWeight = purchaseReceipt.getPlannedWeight();
                        b = (int) Math.round(aDouble) >= (int) Math.round(plannedWeight);
                    } else {
                        int warehousingNum = purchaseReceipt.getWarehousingNum();
                        b = (int) Math.round(aDouble) >= warehousingNum;
                    }

                    if (isTrue && b) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);
                    }

                    //修改采购入库状态
                    updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
                    // 将数据回传至采购订单
                    if (purchaseReceipt.getStatus() == 3) {
                        UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
                        updatePurchaseOrderDataVo.setActualQuantity(purchaseReceipt.getActualQuantity());
                        updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
                        orderFeignService.updateOrderData(updatePurchaseOrderDataVo);
                    }

                    //修改采购打印状态
                    IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getBatchNo, pickingRestDbVo.getInputValue()));
                    incomingMaterialPrinting.setPrintStatus(4);
                    incomingMaterialPrintingService.updateById(incomingMaterialPrinting);
                    //判断该单据在打印页面是否还存在未入库数据
                    String receiptNo = purchaseReceipt.getReceiptNo();
                    List<IncomingMaterialPrinting> incomingMaterialPrintings = incomingMaterialPrintingMapper.selectList(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getReceiptNo, receiptNo));
                    boolean printAll = true;
                    for (IncomingMaterialPrinting entity : incomingMaterialPrintings) {
                        if (entity.getPrintStatus() != 4) {
                            printAll = false;
                            break;
                        }
                    }
                    if (printAll) {
                        purchaseReceipt.setStatus(3);
                    } else {
                        purchaseReceipt.setStatus(2);
                    }
                    updateById(purchaseReceipt);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
            }
            //库位撤销
            if ("3".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("该仓库不存在，请核实");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()).eq(WmsStockInfo::getWsiMaterialStatus, 2));
                    if (wmsStockInfo == null) {
                        pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    wmsStockInfo.setWsiMaterialStatus(1);
                    wmsStockInfo.setWsiWarehourse("");
                    wmsStockInfo.setWsiReservoirArea("");
                    wmsStockInfo.setWsiStorageLoaction("");
                    wmsStockInfo.setWsiWarehourseInfo("");
                    wmsStockInfoMapper.updateById(wmsStockInfo);

                    //获取采购入库信息
                    PurchaseReceipt purchaseReceipt = getById(pickingRestDbVo.getId());
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseReceipt.getMaterialCode()));
                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                    //同时修改采购入库明细状态
                    List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getBatchNo, wmsStockInfo.getWsiMaterialBatch()));
                    for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                        if (entity.getMaterialNumber().equals(pickingRestDbVo.getInputValue())) {
                            entity.setStatus(1);
                            entity.setWarehouseMessage("");
                            entity.setWarehouseInTime(null);
                            entity.setWarehouseInBy("");
                            purchaseReceiptDetailService.updateById(entity);
                        }
                    }
                    //修改采购入库单状态为入库中
                    purchaseReceipt.setStatus(2);
                    updateById(purchaseReceipt);
                    // 将数据回传至采购订单
                    UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
                    updatePurchaseOrderDataVo.setActualQuantity(purchaseReceipt.getActualQuantity());
                    updatePurchaseOrderDataVo.setPurchaseOrderNo(purchaseReceipt.getPurchaseOrderNo());
                    orderFeignService.updateOrderData(updatePurchaseOrderDataVo);

                    //设置返回信息
                    pickingRestDbDto.setMessage("物料号码:" + purchaseReceiptDetailList.get(0).getMaterialNumber() + "," + "净重:" + purchaseReceiptDetailList.get(0).getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + purchaseReceiptDetailList.get(0).getReceiptQuantity() + "," + "撤销成功");
                    pickingRestDbDto.setQuantityIdentification(purchaseReceipt.getPlannedWeight() + "/" + purchaseReceipt.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(purchaseReceipt.getWarehousingNum()));
                    pickingRestDbDto.setCode("200");
                    pickingRestDbDto.setMessage("操作成功");
                    return pickingRestDbDto;
                }
            }
        } else {
            pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
        pickingRestDbDto.setCode("500");
        pickingRestDbDto.setMessage("步骤错误");
        return pickingRestDbDto;
    }

    /**
     * 根据采购订单状态修改采购入库状态(feign调用)
     *
     * @param updateReceiptStatusVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReceiptStatus(UpdateReceiptStatusVo updateReceiptStatusVo) {

        List<PurchaseReceipt> purchaseReceipt = purchaseReceiptMapper.selectList(new QueryWrapper<PurchaseReceipt>().lambda().eq(PurchaseReceipt::getPurchaseOrderNo, updateReceiptStatusVo.getPurchaseOrderNo()));
        if (purchaseReceipt.size() > 0) {
            for (PurchaseReceipt entity : purchaseReceipt) {
                //已完成、已关结不可重复关结；
                if (entity.getStatus() != 3 || entity.getStatus() != 4) {
                    entity.setStatus(updateReceiptStatusVo.getUpdateValue());
                    // 入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库（采购入库未扫描到的条码从库存中删除）
                    List<PurchaseReceiptDetail> purchaseReceiptDetails = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, entity.getId()));
                    if (purchaseReceiptDetails.size() > 0) {
                        //获取未扫描的明细数据
                        List<String> materialNumberList = purchaseReceiptDetails.stream()
                                .filter(t -> t.getStatus() == 1)
                                .map(PurchaseReceiptDetail::getMaterialNumber)
                                .collect(Collectors.toList());
                        //将对应号码的数据在仓库中进行删除
                        if (materialNumberList.size() > 0) {
                            List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                            wmsStockInfoService.removeBatchByIds(wmsStockInfos);
                        }
                    }
                }
            }
            return updateBatchById(purchaseReceipt);
        } else {
            throw new GlobalException("没有查询到相关采购入库单,请核实!");
        }
    }

    /**
     * 安卓pda 列表
     *
     * @param number
     * @return
     */
    @Override
    public List<AndroidPdaDto> androidPdaList(int number) {
        Long deptId = SecurityUtils.getDeptId();
        //采购入库列表
        if (number == 1) {
            return purchaseReceiptMapper.getReceiptAndroidList(deptId);
        } else if (number == 2) {
            //完工入库列表-自动生成
            return wipCompletionMapper.getWipCompletionAndroidList(deptId);
        } else if (number == 3) {
            //完工入库列表-手动生成
            return wipCompletionMapper.getWipCompletionAndroidManualList(deptId);
        } else if (number == 4) {
            //生产退料
            return productionMaterialReturnMapper.getProductionAndroidList(deptId);
        } else if (number == 5) {
            //销售发货
            return salesReturnMapper.getSaleAndroidList(deptId);
        } else if (number == 6) {
            //委外入库
            return subcontractReceiptMapper.getSubcontractAndroidList(deptId);
        } else if (number == 7) {
            //其他入库
            return miscellaneousReceiptMapper.getMiscellaneousAndroidList(deptId);
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 手持pda 查看接口
     *
     * @param number
     * @return
     */
    @Override
    public AndroidPdaViewDto androidPdaView(int number, long id) {
        List<SysDictData> typeArray = DictUtils.getDictCache("android_pda_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //采购入库列表
        if (number == 1) {
            AndroidPdaViewDto receiptViewAndroidById = purchaseReceiptMapper.getReceiptViewAndroidById(id);
            receiptViewAndroidById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return receiptViewAndroidById;
        } else if (number == 2) {
            //完工入库列表-自动生成
            AndroidPdaViewDto wipCompletionViewById = wipCompletionMapper.getWipCompletionViewById(id);
            wipCompletionViewById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return wipCompletionViewById;
        } else if (number == 3) {
            //完工入库列表-手动生成
            AndroidPdaViewDto wipCompletionViewAndroidManualById = wipCompletionMapper.getWipCompletionViewAndroidManualById(id);
            wipCompletionViewAndroidManualById.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return wipCompletionViewAndroidManualById;
        } else if (number == 4) {
            //生产退料
            AndroidPdaViewDto productionByIdAndroid = productionMaterialReturnMapper.getProductionByIdAndroid(id);
            productionByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return productionByIdAndroid;
        } else if (number == 5) {
            //销售退货
            AndroidPdaViewDto saleByIdAndroid = salesReturnMapper.getSaleByIdAndroid(id);
            saleByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return saleByIdAndroid;
        } else if (number == 6) {
            //委外入库
            AndroidPdaViewDto subcontractByIdAndroid = subcontractReceiptMapper.getSubcontractByIdAndroid(id);
            subcontractByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return subcontractByIdAndroid;
        } else if (number == 7) {
            //其他入库
            AndroidPdaViewDto miscellaneousByIdAndroid = miscellaneousReceiptMapper.getMiscellaneousByIdAndroid(id);
            miscellaneousByIdAndroid.setWarehousingTypeDict(typeMap.get(String.valueOf(number)));
            return miscellaneousByIdAndroid;
        } else {
            return null;
        }
    }

    /**
     * 手持pda 拣货撤销列表
     *
     * @param number
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<AndroidPdaDto> pickCancellationList(int number) {
        Long deptId = SecurityUtils.getDeptId();
        if (number == 1) {
            //生产退料
            return productionMaterialReturnMapper.getProductionpickCancellationList(deptId);
        } else if (number == 2) {
            //销售退货
            return salesReturnMapper.getSaleAndroidpickCancellationList(deptId);
        } else if (number == 3) {
            //其他入库
            return miscellaneousReceiptMapper.getMiscellaneousAndroidpickCancellationList(deptId);
        } else if (number == 4) {
            //完工入库-手动生成
            return wipCompletionMapper.getWipCompletionAndroidManualpickCancellationList(deptId);
        } else if (number == 5) {
            //生产领料
            return productionPickingMapper.getWipCompletionAndroidManualpickCancellationList(deptId);
        } else if (number == 6) {
            //委外发货
            return pickingOutsourceMapper.getMiscellaneousAndroidpickCancellationList(deptId);
        } else if (number == 7) {
            //销售发货
            return pickingSaleMapper.getMiscellaneousAndroidpickCancellationList(deptId);
        } else if (number == 8) {
            //其他出库
            return pickingRestMapper.getWipCompletionAndroidManualpickCancellationList(deptId);
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 手持pda 拣货完成
     *
     * @param completionPickingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completionPickingAndroid(CompletionPickingVo completionPickingVo) throws Exception {
        PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
        pickingRestDbVo.setId(completionPickingVo.getId());
        if (completionPickingVo.getNumber() == 4) {
            //生产退料
            return productionMaterialReturnService.pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 5) {
            //销售退货
            return salesReturnService.pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 3) {
            //完工入库-手动生成
            return wipCompletionService.pickingCompleted(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 7) {
            //其他入库
            return miscellaneousReceiptService.pickingCompleted(pickingRestDbVo);
        } else {
            return false;
        }
    }

    /**
     * 手持pda 拣货撤销
     *
     * @param completionPickingVo
     * @return
     * @throws Exception
     */
    @Override
    public boolean pickCancellationAndroid(CompletionPickingVo completionPickingVo) {
        PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
        pickingRestDbVo.setId(completionPickingVo.getId());
        if (completionPickingVo.getNumber() == 1) {
            //生产退料
            return productionMaterialReturnService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 2) {
            //销售退货
            return salesReturnService.pickingCancellation(pickingRestDbVo);
        } else if (completionPickingVo.getNumber() == 3) {
            //其它入库
            return miscellaneousReceiptService.pickingCancellation(pickingRestDbVo);
        } else {
            //完工入库-手动生成
            return wipCompletionService.pickingCancellation(pickingRestDbVo);
        }
    }

    /**
     * 手持pda 交接列表
     *
     * @param number
     * @return
     */
    @Override
    public List<AndroidHandoverPdaDto> androidHandoverList(int number) {

        Long deptId = SecurityUtils.getDeptId();
        //生产退料
        if (number == 1) {
            return productionMaterialReturnMapper.getAndroidHandoverList(deptId);
        } else if (number == 2) {
            //销售退货
            return salesReturnMapper.getAndroidHandoverList(deptId);
        } else if (number == 3) {
            //其它入库
            return miscellaneousReceiptMapper.getAndroidHandoverList(deptId);
        } else if (number == 4) {
            //生产领料
            return productionPickingMapper.getAndroidHandoverList(deptId);
        } else if (number == 5) {
            //委外发货
            return pickingOutsourceMapper.getAndroidHandoverList(deptId);
        } else if (number == 6) {
            //销售发货
            return pickingSaleMapper.getAndroidHandoverList(deptId);
        } else if (number == 7) {
            //返工出库
            return pickingCompleteMapper.getAndroidHandoverList(deptId);
        } else if (number == 8) {
            //采购退货
            return pickingPurchaseMapper.getAndroidHandoverList(deptId);
        } else if (number == 9) {
            //委外退货
            return pickingReturnsMapper.getAndroidHandoverList(deptId);
        } else if (number == 10) {
            //其他出库
            return pickingRestMapper.getAndroidHandoverList(deptId);
        } else if (number == 11) {
            //调拨单
            return allotManagementMapper.getAndroidHandoverList(deptId);
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 手持pda 交接详情
     *
     * @param number
     * @param id
     * @return
     */
    @Override
    public AndroidHandoverPdaDto androidHandoverView(int number, Long id) {
        List<SysDictData> typeArray = DictUtils.getDictCache("android_pda_handover_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //交接方式
        List<SysDictData> methodArray = DictUtils.getDictCache("sys_handover_method");
        Map<String, String> methodMap = methodArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //生产退料
        if (number == 1) {
            AndroidHandoverPdaDto androidHandoverView = productionMaterialReturnMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "生产退料";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 2) {
            //销售退货
            AndroidHandoverPdaDto androidHandoverView = salesReturnMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "销售退货";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 3) {
            //其它入库
            AndroidHandoverPdaDto androidHandoverView = miscellaneousReceiptMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "其他入库";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 4) {
            //生产领料
            AndroidHandoverPdaDto androidHandoverView = productionPickingMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "生产领料";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 5) {
            //委外发货
            AndroidHandoverPdaDto androidHandoverView = pickingOutsourceMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "委外发货";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 6) {
            //销售发货
            AndroidHandoverPdaDto androidHandoverView = pickingSaleMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "销售发货";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 7) {
            //返工出库
            AndroidHandoverPdaDto androidHandoverView = pickingCompleteMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "返工出库";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 8) {
            //采购退货
            AndroidHandoverPdaDto androidHandoverView = pickingPurchaseMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "采购退货";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 9) {
            //委外退货
            AndroidHandoverPdaDto androidHandoverView = pickingReturnsMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "委外退货";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 10) {
            //其他出库
            AndroidHandoverPdaDto androidHandoverView = pickingRestMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "其他出库";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else if (number == 11) {
            //调拨单
            AndroidHandoverPdaDto androidHandoverView = allotManagementMapper.getAndroidHandoverView(id);
            androidHandoverView.setHandoverTypeDict(typeMap.get(String.valueOf(number)));
            androidHandoverView.setHandoverType(String.valueOf(number));
            //获取单据配置信息
            String menuName = "调拨管理";
            Long docConfig = feignService.getIdByMenuName(menuName);
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
            SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
            //交接方式
            androidHandoverView.setHandoverMethodDict(methodMap.get(String.valueOf(sysDocument.getDocHandoverMethod())));
            androidHandoverView.setHandoverMethod(String.valueOf(sysDocument.getDocHandoverMethod()));
            return androidHandoverView;
        } else {
            return null;
        }
    }

    /**
     * 手持pda 交接
     *
     * @param androidHandoverVo
     * @return
     */
    @Override
    public PickingRestHandoverDto androidHandover(AndroidHandoverVo androidHandoverVo) {

        //生产退料
        if (androidHandoverVo.getNumber() == 1) {
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return productionMaterialReturnService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 2) {
            //销售退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return salesReturnService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 3) {
            //其它入库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return miscellaneousReceiptService.handover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 4) {
            //生产领料
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return productionPickingService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 5) {
            //委外发货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingOutsourceService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 6) {
            //销售发货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingSaleService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 7) {
            //反攻出库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingCompleteService.overProduction(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 8) {
            //采购退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingPurchaseService.purchaseHandover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 9) {
            //委外退货
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingReturnsService.overProductionReturns(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 10) {
            //其他出库
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return pickingRestService.pickingRestHandover(pickingRestDbVo);
        } else if (androidHandoverVo.getNumber() == 11) {
            //调拨单
            PickingRestDbVo pickingRestDbVo = new PickingRestDbVo();
            BeanUtils.copyProperties(androidHandoverVo, pickingRestDbVo);
            return allotManagementService.overAllot(pickingRestDbVo);
        } else {
            return new PickingRestHandoverDto();
        }
    }

    /**
     * 批次号生成
     */
    public String batchNoGenerate() {
        String batchNo = "";
        String prefix = "CG";
        //查询缓存
        Object cacheObject = redisService.getCacheObject(VariousKeyEnum.getValue(1));
        if (cacheObject == null) {
            String num = "001";
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            String format = sf.format(new Date());
            batchNo = prefix + format + num;
            //放入缓存
            redisService.setCacheObject(VariousKeyEnum.getValue(1), num);
            return batchNo;
        }
        String s = cacheObject.toString();
        String s1 = addOne(s);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sf.format(new Date());
        batchNo = format + s1;
        //放入缓存
        redisService.setCacheObject(VariousKeyEnum.getValue(1), s1);
        return batchNo;
    }

    //字符串末尾加1
    public String addOne(String testStr) {
        //根据不是数字的字符拆分字符串
        String[] strs = testStr.split("[^0-9]");
        //取出最后一组数字
        String numStr = strs[strs.length - 1];
        //如果最后一组没有数字(也就是不以数字结尾)，抛NumberFormatException异常
        if (numStr != null && numStr.length() > 0) {
            //取出字符串的长度
            int n = numStr.length();
            //将该数字加一
            int num = Integer.parseInt(numStr) + 1;
            String added = String.valueOf(num);
            n = Math.min(n, added.length());
            //拼接字符串
            return testStr.subSequence(0, testStr.length() - n) + added;
        } else {
            throw new NumberFormatException();
        }
    }
}
